#include <jni.h>
#include <string>
#include<android/log.h>

extern "C" JNIEXPORT jstring JNICALL
Java_com_example_jnitest2_MainActivity_stringFromJNI(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());
}


extern "C"
JNIEXPORT void JNICALL
Java_com_example_jnitest2_MainActivity_test(JNIEnv *env, jobject thiz, jintArray i_,
                                            jobjectArray j_) {

     jint* numP = env->GetIntArrayElements(i_,NULL);

     int32_t length = env->GetArrayLength(i_);
     for(int k= 0; k < length; ++k)
     {
         __android_log_print(ANDROID_LOG_DEBUG,"JNI","获取的参数是%d",*(numP+k));
         //修改值
         *(numP + k) = 100;
     }

     //参数3为0，刷新java数组并释放C/C++数组
     //参数3为1，只刷新java数据
     //参数3为2，只释放
     env->ReleaseIntArrayElements(i_,numP,0);

    jint strLen = env->GetArrayLength(j_);
    for(int i = 0; i < strLen; i++)
    {
        jstring  str = static_cast<jstring>(env->GetObjectArrayElement(j_, i));
        //在C语言里不能直接使用jstring
        const char * s = env->GetStringUTFChars(str,0);
        __android_log_print(ANDROID_LOG_DEBUG,"JNI","获取的参数是%s",s);
        env->ReleaseStringUTFChars(str,s);

    }
}extern "C"
JNIEXPORT void JNICALL
Java_com_example_jnitest2_MainActivity_passObject(JNIEnv *env, jobject thiz, jobject bean,
                                                  jstring str_) {
    const char*str = env->GetStringUTFChars(str_,0);

    //反射调用java方法
    //1. 获取java对应的class对象
  jclass beanCls = env->GetObjectClass(bean);
   //2. 找到要调用的方法
   //第三个参数传递的是前面
  jmethodID  getI = env->GetMethodID(beanCls,"getI","()I"); //第一个括号表示参数，I表示返回为int
   jmethodID  setI = env->GetMethodID(beanCls,"setI","(I)V");
  jmethodID  printInfo = env->GetStaticMethodID(beanCls,"printInfo","(Ljava/lang/String;)V");
  jmethodID  printInfo2 = env->GetStaticMethodID(beanCls,"printInfo","(Lcom/example/jnitest2/Bean2;)V");

   //3，调用
  jint i =  env->CallIntMethod(bean,getI);
    __android_log_print(ANDROID_LOG_DEBUG,"JNI","C++调用java getI方法:%d",i);
   env->CallVoidMethod(bean,setI,200);

   jstring str2 = env->NewStringUTF("我是Bean类的静态方法，被C++调用");
   env->CallStaticVoidMethod(beanCls,printInfo,str2);

   //在JNI中创建bean对象
   jclass bean2Cls = env->FindClass("com/example/jnitest2/Bean2");
   //反射创建对象
   //1. 获得一个类的构造方法
   jmethodID  construct = env->GetMethodID(bean2Cls,"<init>","(I)V");

   //2. 调用构造方法创建对象
   jobject  bean2 = env->NewObject(bean2Cls,construct,88);
   env->CallStaticVoidMethod(beanCls,printInfo2,bean2);
   env->DeleteLocalRef(bean2Cls); //find出来的要删除
   env->DeleteLocalRef(bean2);//new出来的也要delete
   //释放局部应用
   env->DeleteLocalRef(str2);

   //反射属性
   jfieldID jfieldId = env->GetFieldID(beanCls,"i","I"); //第三个参数是属性i的类型签名
   env->SetIntField(bean,jfieldId,300);

   env->ReleaseStringUTFChars(str_,str);
}